import chalk from 'chalk';
import fs from 'fs';
import path from 'path';
import process from "process";

/**
* 从当前目录往上递归查找，直到找到包含 ops.conf 的目录
*/
function findRootDirWithOpsConf(startDir) {
    let currentDir = startDir;

    while (true) {
        const candidate = path.join(currentDir, "ops.conf");
        if (fs.existsSync(candidate)) {
            return currentDir; // 找到 ops.conf 的目录
        }
        const parentDir = path.dirname(currentDir);
        if (parentDir === currentDir) {
            // 已经到根目录了还没找到
            return startDir;
        }
        currentDir = parentDir;
    }
}

/**
 * 获取日志文件路径
 */
 function getLogFilePath() {
    const today = new Date();
    const yyyy = today.getFullYear();
    const mm = String(today.getMonth() + 1).padStart(2, '0');
    const dd = String(today.getDate()).padStart(2, '0');
    const filename = `nb-${yyyy}-${mm}-${dd}.log`;

    // 从当前工作目录往上找 ops.conf
    const rootDir = findRootDirWithOpsConf(process.cwd());
    const logDir = path.join(rootDir, "logs");

    if (!fs.existsSync(logDir)) {
        fs.mkdirSync(logDir, { recursive: true });
    }

    return path.join(logDir, filename);
}

async function appendLogFile(message) {
    const filePath = getLogFilePath();
    // 异步写入，每条日志换行
    fs.promises.appendFile(filePath, message + '\n').catch(err => {
        console.error('🛑 写入日志文件失败:', err);
    });
}

/**
 * 统一的日志工具类
 */
export class Logger {
    constructor(moduleName = 'APP') {
        this.moduleName = moduleName;
        this.verbose = process.env.VERBOSE === 'true' || process.argv.includes('--verbose');
    }

    async logToFile(level, message) {
        const time = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
        const logLine = `[${time}] [${level}] [${this.moduleName}] ${message}`;
        await appendLogFile(logLine);
    }

    info(message, ...args) {
        console.log(chalk.blue(`🦶 [${this.moduleName}]`), message, ...args);
        this.logToFile('INFO', [message, ...args].join(' '));
    }

    log(message, ...args) {
        this.logToFile('INFO', [message, ...args].join(' '));
    }

    success(message, ...args) {
        console.log(chalk.green(`✅ [${this.moduleName}]`), message, ...args);
        this.logToFile('SUCCESS', [message, ...args].join(' '));
    }

    warn(message, ...args) {
        console.warn(chalk.yellow(`⚠️  [${this.moduleName}]`), message, ...args);
        this.logToFile('WARN', [message, ...args].join(' '));
    }

    error(message, ...args) {
        console.error(chalk.red(`🛑 [${this.moduleName}]`), message, ...args);
        this.logToFile('ERROR', [message, ...args].join(' '));
    }

    debug(message, ...args) {
        if (this.verbose) {
            console.log(chalk.gray(`🐛 [${this.moduleName}]`), message, ...args);
            this.logToFile('DEBUG', [message, ...args].join(' '));
        }
    }

    step(step, message, ...args) {
        console.log(chalk.cyan(`📋 [${this.moduleName}] 步骤 ${step}:`), message, ...args);
        this.logToFile('STEP', `步骤 ${step}: ${[message, ...args].join(' ')}`);
    }
}

/**
 * 创建模块专用的 Logger 实例
 */
export function createLogger(moduleName) {
    return new Logger(moduleName);
}
